<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
    PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- /fasttmp/mkdist-qt-4.3.5-1211793125/qtopia-core-opensource-src-4.3.5/doc/src/examples/basicdrawing.qdoc -->
<head>
  <title>Qt 4.3: Basic Drawing Example</title>
  <link href="classic.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td align="left" valign="top" width="32"><a href="http://www.trolltech.com/products/qt"><img src="images/qt-logo.png" align="left" width="32" height="32" border="0" /></a></td>
<td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="mainclasses.html"><font color="#004faf">Main&nbsp;Classes</font></a>&nbsp;&middot; <a href="groups.html"><font color="#004faf">Grouped&nbsp;Classes</font></a>&nbsp;&middot; <a href="modules.html"><font color="#004faf">Modules</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">Functions</font></a></td>
<td align="right" valign="top" width="230"><a href="http://www.trolltech.com"><img src="images/trolltech-logo.png" align="right" width="203" height="32" border="0" /></a></td></tr></table><h1 align="center">Basic Drawing Example<br /><small></small></h1>
<p>Files:</p>
<ul>
<li><a href="painting-basicdrawing-renderarea-cpp.html">painting/basicdrawing/renderarea.cpp</a></li>
<li><a href="painting-basicdrawing-renderarea-h.html">painting/basicdrawing/renderarea.h</a></li>
<li><a href="painting-basicdrawing-window-cpp.html">painting/basicdrawing/window.cpp</a></li>
<li><a href="painting-basicdrawing-window-h.html">painting/basicdrawing/window.h</a></li>
<li><a href="painting-basicdrawing-main-cpp.html">painting/basicdrawing/main.cpp</a></li>
<li><a href="painting-basicdrawing-basicdrawing-qrc.html">painting/basicdrawing/basicdrawing.qrc</a></li>
</ul>
<p>The Basic Drawing example shows how to display basic graphics primitives in a variety of styles using the <a href="qpainter.html">QPainter</a> class.</p>
<p><a href="qpainter.html">QPainter</a> performs low-level painting on widgets and other paint devices. The class can draw everything from simple lines to complex shapes like pies and chords. It can also draw aligned text and pixmaps. Normally, it draws in a &quot;natural&quot; coordinate system, but it can in addition do view and world transformation.</p>
<p align="center"><img src="images/basicdrawing-example.png" /></p><p>The example provides a render area, displaying the currently active shape, and lets the user manipulate the rendered shape and its appearance using the <a href="qpainter.html">QPainter</a> parameters: The user can change the active shape (<b>Shape</b>), and modify the <a href="qpainter.html">QPainter</a>'s pen (<b>Pen Width</b>, <b>Pen Style</b>, <b>Pen Cap</b>, <b>Pen Join</b>), brush (<b>Brush Style</b>) and render hints (<b>Antialiasing</b>). In addition the user can rotate a shape (<b>Transformations</b>); behind the scenes we use <a href="qpainter.html">QPainter</a>'s ability to manipulate the coordinate system to perform the rotation.</p>
<p>The Basic Drawing example consists of two classes:</p>
<ul>
<li><tt>RenderArea</tt> is a custom widget that renders multiple copies of the currently active shape.</li>
<li><tt>Window</tt> is the application's main window displaying a <tt>RenderArea</tt> widget in addition to several parameter widgets.</li>
</ul>
<p>First we will review the <tt>Window</tt> class, then we will take a look at the <tt>RenderArea</tt> class.</p>
<a name="window-class-definition"></a>
<h2>Window Class Definition</h2>
<p>The Window class inherits <a href="qwidget.html">QWidget</a>, and is the application's main window displaying a <tt>RenderArea</tt> widget in addition to several parameter widgets.</p>
<pre> class Window : public QWidget
 {
     Q_OBJECT

 public:
     Window();

 private slots:
     void shapeChanged();
     void penChanged();
     void brushChanged();

 private:
     RenderArea *renderArea;
     QLabel *shapeLabel;
     QLabel *penWidthLabel;
     QLabel *penStyleLabel;
     QLabel *penCapLabel;
     QLabel *penJoinLabel;
     QLabel *brushStyleLabel;
     QLabel *otherOptionsLabel;
     QComboBox *shapeComboBox;
     QSpinBox *penWidthSpinBox;
     QComboBox *penStyleComboBox;
     QComboBox *penCapComboBox;
     QComboBox *penJoinComboBox;
     QComboBox *brushStyleComboBox;
     QCheckBox *antialiasingCheckBox;
     QCheckBox *transformationsCheckBox;
 };</pre>
<p>We declare the various widgets, and three private slots updating the <tt>RenderArea</tt> widget: The <tt>shapeChanged()</tt> slot updates the <tt>RenderArea</tt> widget when the user changes the currently active shape. We call the <tt>penChanged()</tt> slot when either of the <a href="qpainter.html">QPainter</a>'s pen parameters changes. And the <tt>brushChanged()</tt> slot updates the <tt>RenderArea</tt> widget when the user changes the painter's brush style.</p>
<a name="window-class-implementation"></a>
<h2>Window Class Implementation</h2>
<p>In the constructor we create and initialize the various widgets appearing in the main application window.</p>
<pre> Window::Window()
 {
     renderArea = new RenderArea;

     shapeComboBox = new QComboBox;
     shapeComboBox-&gt;addItem(tr(&quot;Polygon&quot;), RenderArea::Polygon);
     shapeComboBox-&gt;addItem(tr(&quot;Rectangle&quot;), RenderArea::Rect);
     shapeComboBox-&gt;addItem(tr(&quot;Round Rectangle&quot;), RenderArea::RoundRect);
     shapeComboBox-&gt;addItem(tr(&quot;Ellipse&quot;), RenderArea::Ellipse);
     shapeComboBox-&gt;addItem(tr(&quot;Pie&quot;), RenderArea::Pie);
     shapeComboBox-&gt;addItem(tr(&quot;Chord&quot;), RenderArea::Chord);
     shapeComboBox-&gt;addItem(tr(&quot;Path&quot;), RenderArea::Path);
     shapeComboBox-&gt;addItem(tr(&quot;Line&quot;), RenderArea::Line);
     shapeComboBox-&gt;addItem(tr(&quot;Polyline&quot;), RenderArea::Polyline);
     shapeComboBox-&gt;addItem(tr(&quot;Arc&quot;), RenderArea::Arc);
     shapeComboBox-&gt;addItem(tr(&quot;Points&quot;), RenderArea::Points);
     shapeComboBox-&gt;addItem(tr(&quot;Text&quot;), RenderArea::Text);
     shapeComboBox-&gt;addItem(tr(&quot;Pixmap&quot;), RenderArea::Pixmap);

     shapeLabel = new QLabel(tr(&quot;&amp;Shape:&quot;));
     shapeLabel-&gt;setBuddy(shapeComboBox);</pre>
<p>First we create the <tt>RenderArea</tt> widget that will render the currently active shape. Then we create the <b>Shape</b> combobox, and add the associated items (i.e&#x2e; the different shapes a <a href="qpainter.html">QPainter</a> can draw).</p>
<pre>     penWidthSpinBox = new QSpinBox;
     penWidthSpinBox-&gt;setRange(0, 20);
     penWidthSpinBox-&gt;setSpecialValueText(tr(&quot;0 (cosmetic pen)&quot;));

     penWidthLabel = new QLabel(tr(&quot;Pen &amp;Width:&quot;));
     penWidthLabel-&gt;setBuddy(penWidthSpinBox);</pre>
<p><a href="qpainter.html">QPainter</a>'s pen is a <a href="qpen.html">QPen</a> object; the <a href="qpen.html">QPen</a> class defines how a painter should draw lines and outlines of shapes. A pen has several properties: Width, style, cap and join.</p>
<p>A pen's width can be <i>zero</i> or greater, but the most common width is zero. Note that this doesn't mean 0 pixels, but implies that the shape is drawn as smoothly as possible although perhaps not mathematically correct.</p>
<p>We create a <a href="qspinbox.html">QSpinBox</a> for the <b>Pen Width</b> parameter.</p>
<pre>     penStyleComboBox = new QComboBox;
     penStyleComboBox-&gt;addItem(tr(&quot;Solid&quot;), Qt::SolidLine);
     penStyleComboBox-&gt;addItem(tr(&quot;Dash&quot;), Qt::DashLine);
     penStyleComboBox-&gt;addItem(tr(&quot;Dot&quot;), Qt::DotLine);
     penStyleComboBox-&gt;addItem(tr(&quot;Dash Dot&quot;), Qt::DashDotLine);
     penStyleComboBox-&gt;addItem(tr(&quot;Dash Dot Dot&quot;), Qt::DashDotDotLine);
     penStyleComboBox-&gt;addItem(tr(&quot;None&quot;), Qt::NoPen);

     penStyleLabel = new QLabel(tr(&quot;&amp;Pen Style:&quot;));
     penStyleLabel-&gt;setBuddy(penStyleComboBox);

     penCapComboBox = new QComboBox;
     penCapComboBox-&gt;addItem(tr(&quot;Flat&quot;), Qt::FlatCap);
     penCapComboBox-&gt;addItem(tr(&quot;Square&quot;), Qt::SquareCap);
     penCapComboBox-&gt;addItem(tr(&quot;Round&quot;), Qt::RoundCap);

     penCapLabel = new QLabel(tr(&quot;Pen &amp;Cap:&quot;));
     penCapLabel-&gt;setBuddy(penCapComboBox);

     penJoinComboBox = new QComboBox;
     penJoinComboBox-&gt;addItem(tr(&quot;Miter&quot;), Qt::MiterJoin);
     penJoinComboBox-&gt;addItem(tr(&quot;Bevel&quot;), Qt::BevelJoin);
     penJoinComboBox-&gt;addItem(tr(&quot;Round&quot;), Qt::RoundJoin);

     penJoinLabel = new QLabel(tr(&quot;Pen &amp;Join:&quot;));
     penJoinLabel-&gt;setBuddy(penJoinComboBox);</pre>
<p>The pen style defines the line type. The default style is solid (<a href="qt.html#PenStyle-enum">Qt::SolidLine</a>). Setting the style to none (<a href="qt.html#PenStyle-enum">Qt::NoPen</a>) tells the painter to not draw lines or outlines. The pen cap defines how the end points of lines are drawn. And the pen join defines how two lines join when multiple connected lines are drawn. The cap and join only apply to lines with a width of 1 pixel or greater.</p>
<p>We create <a href="qcombobox.html">QComboBox</a>es for each of the <b>Pen Style</b>, <b>Pen Cap</b> and <b>Pen Join</b> parameters, and adds the associated items (i.e the values of the <a href="qt.html#PenStyle-enum">Qt::PenStyle</a>, <a href="qt.html#PenCapStyle-enum">Qt::PenCapStyle</a> and <a href="qt.html#PenJoinStyle-enum">Qt::PenJoinStyle</a> enums respectively).</p>
<pre>     brushStyleComboBox = new QComboBox;
     brushStyleComboBox-&gt;addItem(tr(&quot;Linear Gradient&quot;),
             Qt::LinearGradientPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Radial Gradient&quot;),
             Qt::RadialGradientPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Conical Gradient&quot;),
             Qt::ConicalGradientPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Texture&quot;), Qt::TexturePattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Solid&quot;), Qt::SolidPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Horizontal&quot;), Qt::HorPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Vertical&quot;), Qt::VerPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Cross&quot;), Qt::CrossPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Backward Diagonal&quot;), Qt::BDiagPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Forward Diagonal&quot;), Qt::FDiagPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Diagonal Cross&quot;), Qt::DiagCrossPattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Dense 1&quot;), Qt::Dense1Pattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Dense 2&quot;), Qt::Dense2Pattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Dense 3&quot;), Qt::Dense3Pattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Dense 4&quot;), Qt::Dense4Pattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Dense 5&quot;), Qt::Dense5Pattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Dense 6&quot;), Qt::Dense6Pattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;Dense 7&quot;), Qt::Dense7Pattern);
     brushStyleComboBox-&gt;addItem(tr(&quot;None&quot;), Qt::NoBrush);

     brushStyleLabel = new QLabel(tr(&quot;&amp;Brush Style:&quot;));
     brushStyleLabel-&gt;setBuddy(brushStyleComboBox);</pre>
<p>The <a href="qbrush.html">QBrush</a> class defines the fill pattern of shapes drawn by a <a href="qpainter.html">QPainter</a>. The default brush style is <a href="qt.html#BrushStyle-enum">Qt::NoBrush</a>. This style tells the painter to not fill shapes. The standard style for filling is <a href="qt.html#BrushStyle-enum">Qt::SolidPattern</a>.</p>
<p>We create a <a href="qcombobox.html">QComboBox</a> for the <b>Brush Style</b> parameter, and add the associated items (i.e&#x2e; the values of the <a href="qt.html#BrushStyle-enum">Qt::BrushStyle</a> enum).</p>
<pre>     otherOptionsLabel = new QLabel(tr(&quot;Other Options:&quot;));
     antialiasingCheckBox = new QCheckBox(tr(&quot;&amp;Antialiasing&quot;));</pre>
<p>Antialiasing is a feature that &quot;smoothes&quot; the pixels to create more even and less jagged lines, and can be applied using <a href="qpainter.html">QPainter</a>'s render hints. <a href="qpainter.html#RenderHint-enum">QPainter::RenderHints</a> are used to specify flags to <a href="qpainter.html">QPainter</a> that may or may not be respected by any given engine.</p>
<p>We simply create a <a href="qcheckbox.html">QCheckBox</a> for the <b>Antialiasing</b> option.</p>
<pre>     transformationsCheckBox = new QCheckBox(tr(&quot;&amp;Transformations&quot;));</pre>
<p>The <b>Transformations</b> option implies a manipulation of the coordinate system that will appear as if the rendered shape is rotated in three dimensions.</p>
<p>We use the <a href="qpainter.html#translate">QPainter::translate</a>(), <a href="qpainter.html#rotate">QPainter::rotate</a>() and <a href="qpainter.html#scale">QPainter::scale</a>() functions to implement this feature represented in the main application window by a simple <a href="qcheckbox.html">QCheckBox</a>.</p>
<pre>     connect(shapeComboBox, SIGNAL(activated(int)),
             this, SLOT(shapeChanged()));
     connect(penWidthSpinBox, SIGNAL(valueChanged(int)),
             this, SLOT(penChanged()));
     connect(penStyleComboBox, SIGNAL(activated(int)),
             this, SLOT(penChanged()));
     connect(penCapComboBox, SIGNAL(activated(int)),
             this, SLOT(penChanged()));
     connect(penJoinComboBox, SIGNAL(activated(int)),
             this, SLOT(penChanged()));
     connect(brushStyleComboBox, SIGNAL(activated(int)),
             this, SLOT(brushChanged()));
     connect(antialiasingCheckBox, SIGNAL(toggled(bool)),
             renderArea, SLOT(setAntialiased(bool)));
     connect(transformationsCheckBox, SIGNAL(toggled(bool)),
             renderArea, SLOT(setTransformed(bool)));</pre>
<p>Then we connect the parameter widgets with their associated slots using the static <a href="qobject.html#connect">QObject::connect</a>() function, ensuring that the <tt>RenderArea</tt> widget is updated whenever the user changes the shape, or any of the other parameters.</p>
<pre>     QGridLayout *mainLayout = new QGridLayout;
     mainLayout-&gt;setColumnStretch(0, 1);
     mainLayout-&gt;setColumnStretch(3, 1);
     mainLayout-&gt;addWidget(renderArea, 0, 0, 1, 4);
     mainLayout-&gt;setRowMinimumHeight(1, 6);
     mainLayout-&gt;addWidget(shapeLabel, 2, 1, Qt::AlignRight);
     mainLayout-&gt;addWidget(shapeComboBox, 2, 2);
     mainLayout-&gt;addWidget(penWidthLabel, 3, 1, Qt::AlignRight);
     mainLayout-&gt;addWidget(penWidthSpinBox, 3, 2);
     mainLayout-&gt;addWidget(penStyleLabel, 4, 1, Qt::AlignRight);
     mainLayout-&gt;addWidget(penStyleComboBox, 4, 2);
     mainLayout-&gt;addWidget(penCapLabel, 5, 1, Qt::AlignRight);
     mainLayout-&gt;addWidget(penCapComboBox, 5, 2);
     mainLayout-&gt;addWidget(penJoinLabel, 6, 1, Qt::AlignRight);
     mainLayout-&gt;addWidget(penJoinComboBox, 6, 2);
     mainLayout-&gt;addWidget(brushStyleLabel, 7, 1, Qt::AlignRight);
     mainLayout-&gt;addWidget(brushStyleComboBox, 7, 2);
     mainLayout-&gt;setRowMinimumHeight(8, 6);
     mainLayout-&gt;addWidget(otherOptionsLabel, 9, 1, Qt::AlignRight);
     mainLayout-&gt;addWidget(antialiasingCheckBox, 9, 2);
     mainLayout-&gt;addWidget(transformationsCheckBox, 10, 2);
     setLayout(mainLayout);

     shapeChanged();
     penChanged();
     brushChanged();
     antialiasingCheckBox-&gt;setChecked(true);

     setWindowTitle(tr(&quot;Basic Drawing&quot;));
 }</pre>
<p>Finally, we add the various widgets to a layout, and call the <tt>shapeChanged()</tt>, <tt>penChanged()</tt>, and <tt>brushChanged()</tt> slots to initialize the application. We also turn on antialiasing.</p>
<pre> void Window::shapeChanged()
 {
     RenderArea::Shape shape = RenderArea::Shape(shapeComboBox-&gt;itemData(
             shapeComboBox-&gt;currentIndex(), IdRole).toInt());
     renderArea-&gt;setShape(shape);
 }</pre>
<p>The <tt>shapeChanged()</tt> slot is called whenever the user changes the currently active shape.</p>
<p>First we retrieve the shape the user has chosen using the <a href="qcombobox.html#itemData">QComboBox::itemData</a>() function. This function returns the data for the given role in the given index in the combobox. We use <a href="qcombobox.html#currentIndex-prop">QComboBox::currentIndex</a>() to retrieve the index of the shape, and the role is defined by the <a href="qt.html#ItemDataRole-enum">Qt::ItemDataRole</a> enum; <tt>IdRole</tt> is an alias for <a href="qt.html#ItemDataRole-enum">Qt::UserRole</a>.</p>
<p>Note that <a href="qt.html#ItemDataRole-enum">Qt::UserRole</a> is only the first role that can be used for application-specific purposes. If you need to store different data in the same index, you can use different roles by simply incrementing the value of <a href="qt.html#ItemDataRole-enum">Qt::UserRole</a>, for example: '<a href="qt.html#ItemDataRole-enum">Qt::UserRole</a> + 1' and '<a href="qt.html#ItemDataRole-enum">Qt::UserRole</a> + 2'. However, it is a good programming practice to give each role their own name: 'myFirstRole = <a href="qt.html#ItemDataRole-enum">Qt::UserRole</a> + 1' and 'mySecondRole = <a href="qt.html#ItemDataRole-enum">Qt::UserRole</a> + 2'. Even though we only need a single role in this particular example, we add the following line of code to the beginning of the <tt>window.cpp</tt> file.</p>
<pre> const int IdRole = Qt::UserRole;</pre>
<p>The <a href="qcombobox.html#itemData">QComboBox::itemData</a>() function returns the data as a <a href="qvariant.html">QVariant</a>, so we need to cast the data to <tt>RenderArea::Shape</tt>. If there is no data for the given role, the function returns <a href="qvariant.html#Type-enum">QVariant::Invalid</a>.</p>
<p>In the end we call the <tt>RenderArea::setShape()</tt> slot to update the <tt>RenderArea</tt> widget.</p>
<pre> void Window::penChanged()
 {
     int width = penWidthSpinBox-&gt;value();
     Qt::PenStyle style = Qt::PenStyle(penStyleComboBox-&gt;itemData(
             penStyleComboBox-&gt;currentIndex(), IdRole).toInt());
     Qt::PenCapStyle cap = Qt::PenCapStyle(penCapComboBox-&gt;itemData(
             penCapComboBox-&gt;currentIndex(), IdRole).toInt());
     Qt::PenJoinStyle join = Qt::PenJoinStyle(penJoinComboBox-&gt;itemData(
             penJoinComboBox-&gt;currentIndex(), IdRole).toInt());

     renderArea-&gt;setPen(QPen(Qt::blue, width, style, cap, join));
 }</pre>
<p>We call the <tt>penChanged()</tt> slot whenever the user changes any of the pen parameters. Again we use the <a href="qcombobox.html#itemData">QComboBox::itemData</a>() function to retrieve the parameters, and then we call the <tt>RenderArea::setPen()</tt> slot to update the <tt>RenderArea</tt> widget.</p>
<pre> void Window::brushChanged()
 {
     Qt::BrushStyle style = Qt::BrushStyle(brushStyleComboBox-&gt;itemData(</pre>
<p>The brushChanged() slot is called whenever the user changes the brush parameter which we retrieve using the <a href="qcombobox.html#itemData">QComboBox::itemData</a>() function as before.</p>
<pre>     if (style == Qt::LinearGradientPattern) {
         QLinearGradient linearGradient(0, 0, 100, 100);
         linearGradient.setColorAt(0.0, Qt::white);
         linearGradient.setColorAt(0.2, Qt::green);
         linearGradient.setColorAt(1.0, Qt::black);
         renderArea-&gt;setBrush(linearGradient);</pre>
<p>If the brush parameter is a gradient fill, special actions are required.</p>
<p>The <a href="qgradient.html">QGradient</a> class is used in combination with <a href="qbrush.html">QBrush</a> to specify gradient fills. Qt currently supports three types of gradient fills: linear, radial and conical. Each of these is represented by a subclass of <a href="qgradient.html">QGradient</a>: <a href="qlineargradient.html">QLinearGradient</a>, <a href="qradialgradient.html">QRadialGradient</a> and <a href="qconicalgradient.html">QConicalGradient</a>.</p>
<p>So if the brush style is <a href="qt.html#BrushStyle-enum">Qt::LinearGradientPattern</a>, we first create a <a href="qlineargradient.html">QLinearGradient</a> object with interpolation area between the coordinates passed as arguments to the constructor. The positions are specified using logical coordinates. Then we set the gradient's colors using the <a href="qgradient.html#setColorAt">QGradient::setColorAt</a>() function. The colors is defined using stop points which are composed by a position (between 0 and 1) and a <a href="qcolor.html">QColor</a>. The set of stop points describes how the gradient area should be filled. A gradient can have an arbitrary number of stop points.</p>
<p>In the end we call <tt>RenderArea::setBrush()</tt> slot to update the <tt>RenderArea</tt> widget's brush with the <a href="qlineargradient.html">QLinearGradient</a> object.</p>
<pre>     } else if (style == Qt::RadialGradientPattern) {
         QRadialGradient radialGradient(50, 50, 50, 70, 70);
         radialGradient.setColorAt(0.0, Qt::white);
         radialGradient.setColorAt(0.2, Qt::green);
         radialGradient.setColorAt(1.0, Qt::black);
         renderArea-&gt;setBrush(radialGradient);
     } else if (style == Qt::ConicalGradientPattern) {
         QConicalGradient conicalGradient(50, 50, 150);
         conicalGradient.setColorAt(0.0, Qt::white);
         conicalGradient.setColorAt(0.2, Qt::green);
         conicalGradient.setColorAt(1.0, Qt::black);
         renderArea-&gt;setBrush(conicalGradient);</pre>
<p>A similar pattern of actions, as the one used for <a href="qlineargradient.html">QLinearGradient</a>, is used in the cases of <a href="qt.html#BrushStyle-enum">Qt::RadialGradientPattern</a> and <a href="qt.html#BrushStyle-enum">Qt::ConicalGradientPattern</a>.</p>
<p>The only difference is the arguments passed to the constructor: Regarding the <a href="qradialgradient.html">QRadialGradient</a> constructor the first argument is the center, and the second the radial gradient's radius. The third argument is optional, but can be used to define the focal point of the gradient inside the circle (the default focal point is the circle center). Regarding the <a href="qconicalgradient.html">QConicalGradient</a> constructor, the first argument specifies the center of the conical, and the second specifies the start angle of the interpolation.</p>
<pre>     } else if (style == Qt::TexturePattern) {
         renderArea-&gt;setBrush(QBrush(QPixmap(&quot;:/images/brick.png&quot;)));</pre>
<p>If the brush style is <a href="qt.html#BrushStyle-enum">Qt::TexturePattern</a> we create a <a href="qbrush.html">QBrush</a> from a <a href="qpixmap.html">QPixmap</a>. Then we call <tt>RenderArea::setBrush()</tt> slot to update the <tt>RenderArea</tt> widget with the newly created brush.</p>
<pre>     } else {
         renderArea-&gt;setBrush(QBrush(Qt::green, style));
     }
 }</pre>
<p>Otherwise we simply create a brush with the given style and a green color, and then call <tt>RenderArea::setBrush()</tt> slot to update the <tt>RenderArea</tt> widget with the newly created brush.</p>
<a name="renderarea-class-definition"></a>
<h2>RenderArea Class Definition</h2>
<p>The <tt>RenderArea</tt> class inherits <a href="qwidget.html">QWidget</a>, and renders multiple copies of the currently active shape using a <a href="qpainter.html">QPainter</a>.</p>
<pre> class RenderArea : public QWidget
 {
     Q_OBJECT

 public:
     enum Shape { Line, Points, Polyline, Polygon, Rect, RoundRect, Ellipse, Arc,
                  Chord, Pie, Path, Text, Pixmap };

     RenderArea(QWidget *parent = 0);

     QSize minimumSizeHint() const;
     QSize sizeHint() const;

 public slots:
     void setShape(Shape shape);
     void setPen(const QPen &amp;pen);
     void setBrush(const QBrush &amp;brush);
     void setAntialiased(bool antialiased);
     void setTransformed(bool transformed);

 protected:
     void paintEvent(QPaintEvent *event);

 private:
     Shape shape;
     QPen pen;
     QBrush brush;
     bool antialiased;
     bool transformed;
     QPixmap pixmap;
 };</pre>
<p>First we define a public <tt>Shape</tt> enum to hold the different shapes that can be rendered by the widget (i.e the shapes that can be rendered by a <a href="qpainter.html">QPainter</a>). Then we reimplement the constructor as well as two of <a href="qwidget.html">QWidget</a>'s public functions: <a href="qwidget.html#minimumSizeHint-prop">minimumSizeHint()</a> and <a href="qwidget.html#sizeHint-prop">sizeHint()</a>.</p>
<p>We also reimplement the <a href="qwidget.html#paintEvent">QWidget::paintEvent</a>() function to be able to draw the currently active shape according to the specified parameters.</p>
<p>We declare several private slots: The <tt>setShape()</tt> slot changes the <tt>RenderArea</tt>'s shape, the <tt>setPen()</tt> and <tt>setBrush()</tt> slots modify the widget's pen and brush, and the <tt>setAntialiased()</tt> and <tt>setTransformed()</tt> slots modify the widget's respective properties.</p>
<a name="renderarea-class-implementation"></a>
<h2>RenderArea Class Implementation</h2>
<p>In the constructor we initialize some of the widget's variables.</p>
<pre> RenderArea::RenderArea(QWidget *parent)
     : QWidget(parent)
 {
     shape = Polygon;
     antialiased = false;
     transformed = false;
     pixmap.load(&quot;:/images/qt-logo.png&quot;);

     setBackgroundRole(QPalette::Base);
     setAutoFillBackground(true);
 }</pre>
<p>We set its shape to be a <b>Polygon</b>, its antialiased property to be false and we load an image into the widget's pixmap variable. In the end we set the widget's background role, defining the brush from the widget's <a href="qwidget.html#palette-prop">palette</a> that will be used to render the background. <a href="qpalette.html#ColorRole-enum">QPalette::Base</a> is typically white.</p>
<pre> QSize RenderArea::sizeHint() const
 {
     return QSize(400, 200);
 }</pre>
<p>The <tt>RenderArea</tt> inherits <a href="qwidget.html">QWidget</a>'s <a href="qwidget.html#sizeHint-prop">sizeHint</a> property holding the recommended size for the widget. If the value of this property is an invalid size, no size is recommended.</p>
<p>The default implementation of the <a href="qwidget.html#sizeHint-prop">QWidget::sizeHint</a>() function returns an invalid size if there is no layout for the widget, and returns the layout's preferred size otherwise.</p>
<p>Our reimplementation of the function returns a <a href="qsize.html">QSize</a> with a 400 pixels width and a 200 pixels height.</p>
<pre> QSize RenderArea::minimumSizeHint() const
 {
     return QSize(100, 100);
 }</pre>
<p><tt>RenderArea</tt> also inherits <a href="qwidget.html">QWidget</a>'s <a href="qwidget.html#minimumSizeHint-prop">minimumSizeHint</a> property holding the recommended minimum size for the widget. Again, if the value of this property is an invalid size, no size is recommended.</p>
<p>The default implementation of <a href="qwidget.html#minimumSizeHint-prop">QWidget::minimumSizeHint</a>() returns an invalid size if there is no layout for the widget, and returns the layout's minimum size otherwise.</p>
<p>Our reimplementation of the function returns a <a href="qsize.html">QSize</a> with a 100 pixels width and a 100 pixels height.</p>
<pre> void RenderArea::setShape(Shape shape)
 {
     this-&gt;shape = shape;
     update();
 }

 void RenderArea::setPen(const QPen &amp;pen)
 {
     this-&gt;pen = pen;
     update();
 }

 void RenderArea::setBrush(const QBrush &amp;brush)
 {
     this-&gt;brush = brush;
     update();
 }</pre>
<p>The public <tt>setShape()</tt>, <tt>setPen()</tt> and <tt>setBrush()</tt> slots are called whenever we want to modify a <tt>RenderArea</tt> widget's shape, pen or brush. We set the shape, pen or brush according to the slot parameter, and call <a href="qwidget.html#update">QWidget::update</a>() to make the changes visible in the <tt>RenderArea</tt> widget.</p>
<p>The <a href="qwidget.html#update">QWidget::update</a>() slot does not cause an immediate repaint; instead it schedules a paint event for processing when Qt returns to the main event loop.</p>
<pre> void RenderArea::setAntialiased(bool antialiased)
 {
     this-&gt;antialiased = antialiased;
     update();
 }

 void RenderArea::setTransformed(bool transformed)
 {
     this-&gt;transformed = transformed;
     update();
 }</pre>
<p>With the <tt>setAntialiased()</tt> and <tt>setTransformed()</tt> slots we change the state of the properties according to the slot parameter, and call the <a href="qwidget.html#update">QWidget::update</a>() slot to make the changes visible in the <tt>RenderArea</tt> widget.</p>
<pre> void RenderArea::paintEvent(QPaintEvent * <span class="comment">/* event */</span>)
 {
     static const QPoint points[4] = {
         QPoint(10, 80),
         QPoint(20, 10),
         QPoint(80, 30),
         QPoint(90, 70)
     };

     QRect rect(10, 20, 80, 60);

     QPainterPath path;
     path.moveTo(20, 80);
     path.lineTo(20, 30);
     path.cubicTo(80, 0, 50, 50, 80, 80);

     int startAngle = 30 * 16;
     int arcLength = 120 * 16;</pre>
<p>Then we reimplement the <a href="qwidget.html#paintEvent">QWidget::paintEvent</a>() function. The first thing we do is to create the graphical objects we will need to draw the various shapes.</p>
<p>We create a vector of four <a href="qpoint.html">QPoint</a>s. We use this vector to render the <b>Points</b>, <b>Polyline</b> and <b>Polygon</b> shapes. Then we create a <a href="qrect.html">QRect</a>, defining a rectangle in the plane, which we use as the bounding rectangle for all the shapes excluding the <b>Path</b> and the <b>Pixmap</b>.</p>
<p>We also create a <a href="qpainterpath.html">QPainterPath</a>. The <a href="qpainterpath.html">QPainterPath</a> class provides a container for painting operations, enabling graphical shapes to be constructed and reused. A painter path is an object composed of a number of graphical building blocks, such as rectangles, ellipses, lines, and curves. For more information about the <a href="qpainterpath.html">QPainterPath</a> class, see the <a href="painting-painterpaths.html">Painter Paths</a> example. In this example, we create a painter path composed of one straight line and a Bezier curve.</p>
<p>In addition we define a start angle and an arc length that we will use when drawing the <b>Arc</b>, <b>Chord</b> and <b>Pie</b> shapes.</p>
<pre>     QPainter painter(this);
     painter.setPen(pen);
     painter.setBrush(brush);
     if (antialiased) {
         painter.setRenderHint(QPainter::Antialiasing, true);</pre>
<p>We create a <a href="qpainter.html">QPainter</a> for the <tt>RenderArea</tt> widget, and set the painters pen and brush according to the <tt>RenderArea</tt>'s pen and brush. If the <b>Antialiasing</b> parameter option is checked, we also set the painter's render hints. <a href="qpainter.html#RenderHint-enum">QPainter::Antialiasing</a> indicates that the engine should antialias edges of primitives if possible.</p>
<pre>     for (int x = 0; x &lt; width(); x += 100) {
         for (int y = 0; y &lt; height(); y += 100) {
             painter.save();
             painter.translate(x, y);</pre>
<p>Finally, we render the multiple copies of the <tt>RenderArea</tt>'s shape. The number of copies is depending on the size of the <tt>RenderArea</tt> widget, and we calculate their positions using two <tt>for</tt> loops and the widgets height and width.</p>
<p>For each copy we first save the current painter state (pushes the state onto a stack). Then we translate the coordinate system, using the <a href="qpainter.html#translate">QPainter::translate</a>() function, to the position determined by the variables of the <tt>for</tt> loops. If we omit this translation of the coordinate system all the copies of the shape will be rendered on top of each other in the top left cormer of the <tt>RenderArea</tt> widget.</p>
<pre>             if (transformed) {
                 painter.translate(50, 50);
                 painter.rotate(60.0);
                 painter.scale(0.6, 0.9);
                 painter.translate(-50, -50);
             }</pre>
<p>If the <b>Transformations</b> parameter option is checked, we do an additional translation of the coordinate system before we rotate the coordinate system 60 degrees clockwise using the <a href="qpainter.html#rotate">QPainter::rotate</a>() function and scale it down in size using the <a href="qpainter.html#scale">QPainter::scale</a>() function. In the end we translate the coordinate system back to where it was before we rotated and scaled it.</p>
<p>Now, when rendering the shape, it will appear as if it was rotated in three dimensions.</p>
<pre>             switch (shape) {
             case Line:
                 painter.drawLine(rect.bottomLeft(), rect.topRight());
                 break;
             case Points:
                 painter.drawPoints(points, 4);
                 break;
             case Polyline:
                 painter.drawPolyline(points, 4);
                 break;
             case Polygon:
                 painter.drawPolygon(points, 4);
                 break;
             case Rect:
                 painter.drawRect(rect);
                 break;
             case RoundRect:
                 painter.drawRoundRect(rect);
                 break;
             case Ellipse:
                 painter.drawEllipse(rect);
                 break;
             case Arc:
                 painter.drawArc(rect, startAngle, arcLength);
                 break;
             case Chord:
                 painter.drawChord(rect, startAngle, arcLength);
                 break;
             case Pie:
                 painter.drawPie(rect, startAngle, arcLength);
                 break;
             case Path:
                 painter.drawPath(path);
                 break;
             case Text:
                 painter.drawText(rect, Qt::AlignCenter, tr(&quot;Qt by\nTrolltech&quot;));
                 break;
             case Pixmap:
                 painter.drawPixmap(10, 10, pixmap);
             }</pre>
<p>Next, we identify the <tt>RenderArea</tt>'s shape, and render it using the associated <a href="qpainter.html">QPainter</a> drawing function:</p>
<ul>
<li><a href="qpainter.html#drawLine">QPainter::drawLine</a>(),</li>
<li><a href="qpainter.html#drawPoints">QPainter::drawPoints</a>(),</li>
<li><a href="qpainter.html#drawPolyline">QPainter::drawPolyline</a>(),</li>
<li><a href="qpainter.html#drawPolygon">QPainter::drawPolygon</a>(),</li>
<li><a href="qpainter.html#drawRect">QPainter::drawRect</a>(),</li>
<li><a href="qpainter.html#drawRoundRect">QPainter::drawRoundRect</a>(),</li>
<li><a href="qpainter.html#drawEllipse">QPainter::drawEllipse</a>(),</li>
<li><a href="qpainter.html#drawArc">QPainter::drawArc</a>(),</li>
<li><a href="qpainter.html#drawChord">QPainter::drawChord</a>(),</li>
<li><a href="qpainter.html#drawPie">QPainter::drawPie</a>(),</li>
<li><a href="qpainter.html#drawPath">QPainter::drawPath</a>(),</li>
<li><a href="qpainter.html#drawText">QPainter::drawText</a>() or</li>
<li><a href="qpainter.html#drawPixmap">QPainter::drawPixmap</a>()</li>
</ul>
<p>Before we started rendering, we saved the current painter state (pushes the state onto a stack). The rationale for this is that we calculate each shape copy's position relative to the same point in the coordinate system. When translating the coordinate system, we lose the knowledge of this point unless we save the current painter state <i>before</i> we start the translating process.</p>
<pre>             painter.restore();
         }
     }

     painter.setPen(palette().dark().color());
     painter.setBrush(Qt::NoBrush);
     painter.drawRect(QRect(0, 0, width() - 1, height() - 1));
 }</pre>
<p>Then, when we are finished rendering a copy of the shape we can restore the original painter state, with its associated coordinate system, using the <a href="qpainter.html#restore">QPainter::restore</a>() function. In this way we ensure that the next shape copy will be rendered in the correct position.</p>
<p>We could translate the coordinate system back using <a href="qpainter.html#translate">QPainter::translate</a>() instead of saving the painter state. But since we in addition to translating the coordinate system (when the <b>Transformation</b> parameter option is checked) both rotate and scale the coordinate system, the easiest solution is to save the current painter state.</p>
<p /><address><hr /><div align="center">
<table width="100%" cellspacing="0" border="0"><tr class="address">
<td width="30%">Copyright &copy; 2008 <a href="trolltech.html">Trolltech</a></td>
<td width="40%" align="center"><a href="trademarks.html">Trademarks</a></td>
<td width="30%" align="right"><div align="right">Qt 4.3.5</div></td>
</tr></table></div></address></body>
</html>
